package com.example.jwtlearning.controller;

import com.example.jwtlearning.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/08/09
 * @Description:
 */
@RestController
public class LoginController {
    /**
     * 根据账号和密码进行登录
     * @param username
     * @param pwd
     * @author: anlu
     * @time: 2021/8/9
     */
    @GetMapping(value = "/login")
    public String login(String username,String pwd){
        //在这里进行用户身份校验

        //校验身份成功生成token返回
        //生成密匙
        SecretKey key = JWTUtils.generalKey();
        String jwt = JWTUtils.createJWT("1",username,10000*60,key);
        System.out.println("生成的token="+jwt);
        System.out.println(JWTUtils.parseJWT(jwt,key));
        return jwt;

    }


    // 这里只大致写一些，具体验证失败原因以及返回格式问题可以根据自身细调
    @RequestMapping(value = "/index")
    public String toIndex(HttpServletRequest request){

        //生成密匙
        SecretKey key = JWTUtils.generalKey();

        //获取token
        String authorization = request.getHeader("authorization");

        if(authorization == null){
            //返回登陆
            return "login";
        }else{
            //进行校验
            authorization=authorization.replaceAll(" +","+");
            try{
                System.out.println(JWTUtils.parseJWT(authorization,key));
//                Claims claims = JWTUtils.parseJWT(authorization);
                Claims claims = JWTUtils.parseJWT(authorization,key);
                return "success";
            }catch (Exception e){
                e.printStackTrace();
                return "fail";
            }
        }

    }

}
